package cn.com.bluemoon.daps.common.sql.layer;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * druid sql parser 解析sql
 *
 * @author Jarod.Kong
 * @date 2021/1/21 15:17
 */
@Slf4j
public class DruidLayerCheck implements ILayerCheck {

    /**
     * 解析SQL（单条）
     *
     * @param dbType
     * @param sql
     * @return
     */
    @Override
    public void checkSingle(DbType dbType, String sql, LayerCallback callback) {
        String message = null;
        try {
            SQLUtils.parseSingleStatement(sql, dbType);
            SQLUtils.format(sql, dbType);
        } catch (Exception e) {
            log.error("SQL语法错误", e);
            message = e.getMessage();
        } finally {
            callback.callback(message);
        }
    }

    @Override
    public void check(DbType dbType, String sql, LayerCallback callback) {
        String message = null;
        try {
            SQLUtils.parseStatements(sql, dbType);
            SQLUtils.format(sql, dbType);
        } catch (Exception e) {
            log.error("SQL=>{}语法错误", sql, e);
            message = String.format("定制DDL=>%s，语法错误", sql);
        } finally {
            callback.callback(message);
        }
    }

    @Override
    public String getFormatSql(String sql, DbType dbType, SQLUtils.FormatOption formatOption) {
        return SQLUtils.format(sql, dbType, formatOption);
    }

    @Override
    public String getFormatSql(String sql, DbType dbType) {
        SQLUtils.FormatOption formatOption = new SQLUtils.FormatOption();
        formatOption.setPrettyFormat(true);
        formatOption.setUppCase(false);
        return getFormatSql(sql, dbType, formatOption);
    }

    @Override
    public String getFormatMysqlSql(String sql) {
        return this.getFormatSql(sql, DbType.mysql, new SQLUtils.FormatOption());
    }
}
